package net.dlz.example.controller;

import net.dlz.example.domain.JavaMailUtils;
import net.dlz.example.domain.SearchApplicationResponse;
import net.dlz.example.domain.SearchUserResponse;
import net.dlz.example.domain.User;
import net.dlz.example.service.ApplicationService;
import net.dlz.example.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private ApplicationService applicationService;

    @RequestMapping("index")
    public String Index(){return "index";}

    @RequestMapping("/toregister")
    public String registerPage() {
        return "user_register";
    }

    //邮箱验证码
    @PostMapping(value = "/registerCode")
    public void registerCode(HttpServletResponse response, HttpServletRequest request, HttpSession session, String email) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        Random rm = new Random();
        String code ="";
        for(int i = 0;i<4;i++) {
            int num = rm.nextInt(26) + 65;
            code += (char) num;
        }
        JavaMailUtils.sendMail(email,code);
        session=request.getSession(true);
        session.setAttribute("code",code);
        session.setAttribute("email" ,email);
        session.setMaxInactiveInterval(60);
    }
    @RequestMapping("/mail")
    @ResponseBody
    public Map<String,String> editPassword(@RequestParam("email")String email,
                                           @RequestParam(value = "password",required = false)String password) {
        Map<String, String> map = new HashMap<>();
        User user = new User();
        if(userService.exist(email)>0){
            user.setUserPassword(password);
            if (email.equals("")|| password.equals("")) {
                map.put("code", "0");
                map.put("msg", "当前信息有空值，请检查");
                return map;
            } else {
                map.put("code", "2");
                map.put("msg", "用户信息修改成功！");
                userService.updateByEmail(user,email);
                return map;
            }
        }else {
            map.put("code", "1");
            map.put("msg", "不存在此邮箱！");
            return map;
        }
    }


    @RequestMapping("/register")
    public String register(Model model, @ModelAttribute User user,@RequestParam("confirm") String password) {
        String msge = null;
        if (StringUtils.isBlank(user.getUserName())) {
            msge = "用户名不能为空";
            model.addAttribute("msge", msge);
            return "user_register";
        } else if (StringUtils.isBlank(user.getUserPassword())) {
            msge = "密码不能为空";
            model.addAttribute("msge", msge);
            return "user_register";
        } else if (StringUtils.isBlank(password) || !password.equals(user.getUserPassword())) {
            msge = "两次密码输入不一致";
            model.addAttribute("msge", msge);
            return "user_register";
        } else {
            int updated = userService.saveUser(user);
            msge = "注册成功，立即登录";
            model.addAttribute("msge", msge);
            return "user_login";
        }
    }


    @RequestMapping("/tologin")
    public String tologin() {
        return "user_login";
    }

    @RequestMapping("/login")
    public String login(Model model,String userName, String password, HttpSession session) {
        User user = userService.findUserByName(userName);
        String msg = null;
        if (user == null) {
            msg = "用户名不存在";
            model.addAttribute("msg", msg);
            return "user_login";
        } else {
            String pwd = user.getUserPassword();
            if (password != null && pwd.equals(password)) {
                msg = "登录成功";
                model.addAttribute("msg", msg);
                session.setAttribute("current_user", user);
                return "user_page";
            } else {
                msg = "密码错误";
                model.addAttribute("msg", msg);
                return "user_login";
            }

        }

    }

    @RequestMapping("/save")
    @ResponseBody
    public Boolean UserSave(User user){
        int deleted = userService.saveUser(user);
        return deleted >0;
    }

    @RequestMapping("/tomes")
    public String Usermes(){
        return "user_mes";
    }

    @RequestMapping("/add")
    public String addUser(User user){
        int updated = userService.saveUser(user);
        return "user_edit";
    }

    @RequestMapping("/form")
    public String UserForm(Model model, @RequestParam("id") String id) {
        User user = userService.findUserByPrimaryKey(id);
        model.addAttribute("user", user);
        return "user_form";
    }

    @GetMapping("/api/search")
    @ResponseBody
    public SearchUserResponse searchUserReponse(@RequestParam("pageNum") Integer pageNum,
                                                @RequestParam("pageSize") Integer pageSize){
        return userService.findAllUser(pageNum,pageSize);
    }
    @GetMapping("/api/searchLink")
    @ResponseBody
    public SearchUserResponse searchUserReponseLink(@RequestParam("pageNum") Integer pageNum,
                                                    @RequestParam("keywords") String keywords,
                                                    @RequestParam("pageSize") Integer pageSize){
        System.out.println(keywords);
        return userService.findUserLinkName(pageNum,keywords,pageSize);
    }

    @DeleteMapping("/delete")
    @ResponseBody
    public Boolean deleteUser(@RequestParam("userid") String userid) {
        int delete = userService.deleteUser(userid);
        return delete > 0;
    }

    @RequestMapping("/list")
    public  String UserList(){
        return "user_list";
    }

//    @RequestMapping(value = "/search", method = RequestMethod.GET)
//    public String userPage(Model model) {
//        //TODO:Add User search result
//        List<User> users = userService.listUser();
//        Model users1 = model.addAttribute("users", users);
//        return "user_list";
//    }

    @RequestMapping("/toedit")
    public String Useredit(Model model, HttpServletRequest request){
        HttpSession session = request.getSession();
        User current_user = (User)session.getAttribute("current_user");
        User user = userService.findUserByPrimaryKey(current_user.getUserId());
        model.addAttribute("user",user);
        return "user_edit";
    }

    @RequestMapping("/toadd")
    public String add() {
        return "user_list";
    }


//    @GetMapping("/api/searchByUser")
//    @ResponseBody
//    public SearchApplicationResponse searchApplyResponseByUser(@RequestParam("id") String id,
//                                                               @RequestParam("pageNum") Integer pageNum,
//                                                               @RequestParam("pageSize") Integer pageSize){
//        return applicationService.findApplicationByUser(id,pageNum,pageSize);
//    }
//    @GetMapping("/api/searchLinkByUser")
//    @ResponseBody
//    public SearchApplicationResponse searchUserReponseLink(@RequestParam("pageNum") String pageNum,
//                                                           @RequestParam("id") String id,
//                                                           @RequestParam("keywords") Integer keywords,
//                                                           @RequestParam("pageSize") Integer pageSize){
//        System.out.println(keywords);
//        return applicationService.findApplicationLinkByUser(pageNum,id,keywords,pageSize);
//    }
//
//    @RequestMapping("/update")
//    public String update(){return "update";}
//
//    @PostMapping("/updatepwd")
//    public String updatePassword(Model model,HttpSession session,@RequestParam String newPassword,
//                                 @RequestParam String rePassword){
//        User current_user = (User) session.getAttribute("current_user");
//        User user = userService.findUserByPrimaryKey(current_user.getUserId());
//        String mesgg = null;
//        if (StringUtils.isBlank(newPassword) || StringUtils.isBlank(rePassword)) {
//            mesgg = "密码不能为空";
//            model.addAttribute("mesgg", mesgg);
//            return "/user/update";
//        }else if (!newPassword.equals(rePassword)) {
//            mesgg = "两次密码不一致";
//            model.addAttribute("mesgg", mesgg);
//            return "/user/update";
//        }else {
//            user.setUserPassword(newPassword);
//            int updated = userService.saveUser(user);
//        }
//        return "redirect:/user/tregister";
//    }



    @RequestMapping("/tlogin")
    public String tlogin(){
        return "user_register";
    }
    @RequestMapping("/tregister")
    public String tregister(){
        return "user_login";
    }
}